import { streamApiService } from './streamApi';

// 上传文件返回的数据类型
export interface UploadResult {
  docId: string;
  filename: string;
}

// 上传响应类型
export interface UploadResponse {
  code: number;
  message: string;
  data?: UploadResult;
}

// 上传文件的API函数
export const uploadFile = async (file: File, sessionId?: string): Promise<UploadResult> => {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('session_id', sessionId || streamApiService.getSessionId());

  const response = await fetch('/langchain-backend/upload', {
    method: 'POST',
    body: formData,
  });

  if (!response.ok) {
    throw new Error(`上传失败: ${response.status} ${response.statusText}`);
  }

  const result: UploadResponse = await response.json();
  
  if (result.code === 200 && result.data) {
    return result.data;
  } else {
    throw new Error(result.message || '上传失败');
  }
};

// 验证文件类型的函数
export const validateFileType = (file: File): boolean => {
  const allowedTypes = [
    // 文档类型
    '.pdf', '.doc', '.docx', '.ppt', '.pptx', '.xls', '.xlsx', '.txt', '.csv', '.md',
    // 图片类型
    '.jpg', '.jpeg', '.png'
  ];
  
  const fileExtension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
  return allowedTypes.includes(fileExtension);
};

// 验证文件大小的函数
export const validateFileSize = (file: File, maxSizeMB: number = 10): boolean => {
  return file.size / 1024 / 1024 <= maxSizeMB;
};

// 获取支持的文件类型错误信息
export const getFileTypeErrorMessage = (): string => {
  return '不支持的文件类型，请上传PDF、Word、PPT、Excel、图片等格式的文件';
};

// 获取文件大小错误信息
export const getFileSizeErrorMessage = (maxSizeMB: number = 10): string => {
  return `文件大小不能超过${maxSizeMB}MB`;
};
